package com.jvyou.house.controller;

import com.jvyou.common.annotation.Log;
import com.jvyou.common.core.controller.BaseController;
import com.jvyou.common.core.domain.AjaxResult;
import com.jvyou.common.core.domain.entity.SysUser;
import com.jvyou.common.core.page.TableDataInfo;
import com.jvyou.common.enums.BusinessType;
import com.jvyou.common.utils.poi.ExcelUtil;
import com.jvyou.house.domain.Contract;
import com.jvyou.house.domain.House;
import com.jvyou.house.domain.MailSendInfo;
import com.jvyou.house.sender.MailSander;
import com.jvyou.house.service.IContractService;
import com.jvyou.house.service.IHouseService;
import com.jvyou.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 合同Controller
 *
 * @author Jvyou
 * @date 2024-09-16
 */
@RestController
@RequestMapping("/contract/contract")
public class ContractController extends BaseController {
    @Autowired
    private IContractService contractService;

    @Resource
    private MailSendInfo mailSendInfo;

    @Autowired
    private MailSander mailSander;

    @Autowired
    private IHouseService houseService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询合同列表
     */
    @PreAuthorize("@ss.hasPermi('contract:contract:list')")
    @GetMapping("/list")
    public TableDataInfo list(Contract contract) {
        startPage();
        List<Contract> list = contractService.selectContractList(contract);
        return getDataTable(list);
    }

    /**
     * 导出合同列表
     */
    @PreAuthorize("@ss.hasPermi('contract:contract:export')")
    @Log(title = "合同", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Contract contract) {
        List<Contract> list = contractService.selectContractList(contract);
        ExcelUtil<Contract> util = new ExcelUtil<Contract>(Contract.class);
        util.exportExcel(response, list, "合同数据");
    }

    /**
     * 获取合同详细信息
     */
    @PreAuthorize("@ss.hasPermi('contract:contract:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(contractService.selectContractById(id));
    }

    /**
     * 新增合同
     */
    @Log(title = "合同", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Contract contract) {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = userDetails.getUsername();
        SysUser sysUser = sysUserService.selectUserByUserName(username);

        contract.setBuyerId(sysUser.getUserId());
        // 找到房子
        House house = houseService.selectHouseById(contract.getHouseId());
        BigDecimal time = BigDecimal.valueOf(contract.getRentalPeriod());
        //添加邮件发送的信息
        mailSendInfo.setSubject("购房合同");
        mailSendInfo.setContent("<h1>购房合同</h1>" +
                "<p>甲乙双方经友好协商，就以下房产的购房事宜达成如下协议：</p>\n" +
                "        <p>1. 房屋位于 " + house.getHouseName() + "，总面积为 " + house.getArea() + " 平方米。</p>\n" +
                "        <p>2. 购房款总计为 " + house.getRent().multiply(time) + " 元，乙方应在合同签订之日起 10 天内支付全款。</p>\n" +
                "        <p>3. 甲方应在乙方付款后 10 天内将房屋交付给乙方。</p>\n" +
                "        <p>4. 本合同一式两份，甲乙双方各执一份，自签字之日起生效。</p>");
        List<String> addresses = new ArrayList<>();
        addresses.add(house.getContactEmail());
        addresses.add(contract.getBuyerPhone()); // 联系方式暂时为邮箱
        mailSendInfo.setToAddresses(addresses);
        //发送邮件
        mailSander.sendMail(mailSendInfo);
        return toAjax(contractService.insertContract(contract));
    }

    /**
     * 修改合同
     */
    @PreAuthorize("@ss.hasPermi('contract:contract:edit')")
    @Log(title = "合同", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Contract contract) {
        return toAjax(contractService.updateContract(contract));
    }

    /**
     * 删除合同
     */
    @PreAuthorize("@ss.hasPermi('contract:contract:remove')")
    @Log(title = "合同", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(contractService.deleteContractByIds(ids));
    }
}
